package com.comp6231.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.comp6231.replica1.exception.LogOperationException;

/**
 * 
 * @author sknarula (narula.sk@gmail.com)
 * @since September 2013
 * 
 * This class will be used to create a Log and
 * save it in a file as instructed by the class
 * calling it.
 *
 */
public class Log {
	/**
	 * Attributes of the log, fileName contains the 
	 * name of the file where the information like
	 * operation, time, by and message will be saved
	 */
	private String fileName;
	private String operation;
	private String operationBy;
	private String message;
	
	/**
	 * Attributes to write to a file
	 */
	BufferedWriter bout;
    PrintWriter out;
    static String newLine = System.getProperty("line.separator");
	
	/**
	 * 
	 * @param fileName
	 * @param operation
	 * @param operationBy
	 * @param message
	 * 
	 * The class constructor
	 * @throws LogOperationException 
	 */
	public Log (String fileName, String operation, String operationBy, String message) throws LogOperationException {
		this.fileName = fileName;
		this.operation = operation;
		this.operationBy = operationBy;
		this.message = message;
		
		try {
			bout = new BufferedWriter(new FileWriter(new File(fileName), true));
			out = new PrintWriter(bout);
		} catch (IOException e) {
			throw new LogOperationException("Error opening a file");
		}
       
	}
	
	public boolean save() throws LogOperationException {		
        
        try {
        	out.print(this.toString());        
            out.print(newLine);
            out.flush();
            out.close();
			bout.close();
		} catch (IOException e) {
			throw new LogOperationException("Error closing the log file");
		} catch (Exception e) {
			throw new LogOperationException("Error saving the log");
		}
        return true;
	}
	
	@Override
	public String toString() {
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		
		return "Log [" + operation + ", on " + dateFormat.format(date)
				+ " From " + operationBy + ", message=" + message + "]";
	}

	/**
	 * Getters and Setters
	 */
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getOperation() {
		return operation;
	}

	public void setOperation(String operation) {
		this.operation = operation;
	}

	public String getOperationBy() {
		return operationBy;
	}

	public void setOperationBy(String operationBy) {
		this.operationBy = operationBy;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
}
